from io import BytesIO

from flask import Flask,request,jsonify

from ajaxUtils import res
from ocrCore import CPUOptimizedOCR

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024  # 20MB限制
ocr_engine = CPUOptimizedOCR()


@app.route('/')
def hello_world():
    return '!!!!智写通OCR离线识别库!!!!'


@app.route('/ocr', methods=['POST'])
def ocr_endpoint():
    if 'file' not in request.files:
        return jsonify(res(400,'文件不存在')), 400

    file = request.files['file']
    if not file.filename:
        return jsonify(res(400,'文件名为空')), 400

    try:
        # 内存处理
        in_memory = BytesIO()
        file.save(in_memory)
        in_memory.seek(0)

        # 执行识别
        result = ocr_engine.recognize(in_memory)

        if 'error' in result:
            return jsonify(res(500,'识别失败!!',result['error'])), 500

        return jsonify(res(200,'识别成功',result)), 200

    except Exception as e:
        return jsonify({"status": 500, "message": str(e)}), 500


if __name__ == '__main__':
    print('!!!!智写通OCR离线识别库启动!!!!')
    app.run(host='0.0.0.0', port=5000, debug=True)
